import Taro from '@tarojs/taro'
import { View, Text, Image, Navigator, Button } from '@tarojs/components'
import { AtFloatLayout } from 'taro-ui'
import DrawQRCode from 'weapp-qrcode'

import QRCode2Base64 from '../../weapp-qrcode'
import { getPartner } from '../../api/home'
import { showToast, getUpdatePage } from '../../utils'

import './index.less'

const pagePaddingTop = Taro.getMenuButtonBoundingClientRect().bottom
const headPaddingTop = Taro.getMenuButtonBoundingClientRect().height
const settingPositionTop = pagePaddingTop - 20 - (headPaddingTop - 20) / 2

Taro.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline']
})

class Home extends Taro.Component {
  config = {
    navigationStyle: 'custom',
    enablePullDownRefresh: true,
    navigationBarTextStyle: 'white'
  }

  state = {
    info: {},
    isShowShare: false,
    base64QRCode: '',
    isToken: false,
    isSave: false
  }

  onPullDownRefresh() {
    this.getData()
  }
  
  getData = async () => {
    Taro.showLoading()

    const res = await getPartner()

    Taro.hideLoading()

    if (res.code === 1) {
      Taro.stopPullDownRefresh()
      this.setState({
        info: res.data
      })
    }
  }

  componentDidMount() {
    Taro.getStorage({
      key: 'token',
      success: () => {
        this.getData()

        this.setState({
          isToken: true
        })
      }
    })
  }

  componentDidShow() {
    getUpdatePage(this.getData)
  }

  share = async () => {
    if (!this.state.isToken) {
      Taro.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    
    this.setState({
      isShowShare: true
    })

    if (this.state.QRCode2Base64) return

    const id = await Taro.getStorage({key: 'id'})
    const registerUrl = `http://erp.webapi${process.env.NODE_ENV === 'production' ? '' : '.testing'}.cl-zenith.com/html/AIBookShare/register.html?agentId=${id.data}&typeId=3`

    this.setState({
      QRCode2Base64: QRCode2Base64.drawImg(registerUrl, {
        typeNumber: 4,
        errorCorrectLevel: 'M',
        size: 500
      })
    })

    DrawQRCode({
      width: 240,
      height: 240,
      canvasId: 'shareQRCode',
      text: registerUrl,
      correctLevel: 0,
      callback: () => {
        setTimeout(async () => {
          const QRCode = await Taro.canvasToTempFilePath({canvasId: 'shareQRCode'})
          const ctx = Taro.createCanvasContext('shareCanvas')

          ctx.drawImage(require('../../assets/images/page.png'), 0, 0, 750, 1334)
          ctx.drawImage(QRCode.tempFilePath, 452, 1038, 240, 240)
          ctx.draw()

          this.setState({
            isSave: true
          })
        }, 100)
      }
    })
  }

  savePic = async () => {
    Taro.showLoading()

    const { tempFilePath } = await Taro.canvasToTempFilePath({canvasId: 'shareCanvas'})
    
    Taro.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: () => {
        Taro.hideLoading()
        showToast('保存成功！')
      },
      fail: () => {
        Taro.hideLoading()
        showToast('保存失败！')
      },
      complete: () => {
        this.setState({
          isShowShare: false
        })
      }
    })
  }

  shareClose = () => {
    this.setState({
      isShowShare: false
    })
  }

  logout = () => {
    Taro.showModal({
      content: '确定要退出吗？',
      success: res => {
        if (res.confirm) {
          Taro.clearStorage({
            success: () => {
              showToast('退出成功！')

              Taro.navigateTo({
                url: '/pages/login/index'
              })
            },
            fail: () => {
              showToast('退出失败！')
            }
          })
        }
      }
    })
  }

  render() {
    const {
      imgUrl,
      levelName = '-',
      name = '请登录您的账号', 
      number = '',
      lowerPartnerAmount = '-',
      memberAmount = '-',
      accountBalance = '-',
      pendingSettlement = '-',
      totalMember = '-',
      partnerCount = '-',
      orderCount = '-'
    } = this.state.info
    const { isShowShare, QRCode2Base64, isToken, isSave } = this.state

    return (
      <View className="home" style={{ paddingTop: pagePaddingTop + 'Px' }}>
        {
          isToken
          ?
          <Image
            onClick={ this.logout }
            style={{ top: settingPositionTop + 'Px' }}
            className="setting"
            src={ require('../../assets/images/logout.png') }
          />
          :
          null
        }
        <View className="user-info">
          <Navigator url="/pages/profile/index" hoverClass="none" className="info">
            <Image src={ imgUrl ? imgUrl : require('../../assets/images/head_pic.png') } />
            <View className="name">
              <Navigator className="uname" url="/pages/profile/index">{ name }</Navigator>
              {
                isToken
                ? <Text>代理编号：{ number }</Text>
                : <Navigator className="login" url="/pages/login/index">点击登录</Navigator>
              }
            </View>
          </Navigator>
          <View className="stick">{ levelName }</View>
        </View>
        <View className="statistics">
          <View>累计售出{ lowerPartnerAmount + memberAmount }，下级代理{ lowerPartnerAmount }，会员{ memberAmount }</View>
          <View>
            <Navigator url="/pages/transaction/index" hoverClass="none" className="item">
              <View className="money">{ accountBalance }</View>
              <View className="item">
                <Text>货款余额</Text>
                <View className="at-icon at-icon-chevron-right" />
              </View>
            </Navigator>
            <View className="item">
              <View className="money">{ pendingSettlement }</View>
              <View>
                <Text>待结算</Text>
                {/* <View className="at-icon at-icon-chevron-right" /> */}
              </View>
            </View>
          </View>
        </View>
        <View className="list">
          <Navigator url="/pages/myMember/index" className="item">
            <View>
              <Text>我的会员</Text>
              <Text>{ totalMember }人</Text>
            </View>
            <Image src={ require('../../assets/images/home_icon1.png') } />
          </Navigator>
          <Navigator url="/pages/partner/index" className="item">
            <View>
              <Text>我的合伙人</Text>
              <Text>{ partnerCount }人</Text>
            </View>
            <Image src={ require('../../assets/images/home_icon2.png') } />
          </Navigator>
          <Navigator url="/pages/order/index" className="item">
            <View>
              <Text>我的订单</Text>
              <Text>{ orderCount }笔</Text>
            </View>
            <Image src={ require('../../assets/images/home_icon3.png') } />
          </Navigator>
          <View className="item" onClick={ this.share }>
            <View>
              <Text>一键分享</Text>
              <Text>点击分享</Text>
            </View>
            <Image src={ require('../../assets/images/home_icon4.png') } />
          </View>
        </View>
        <AtFloatLayout isOpened={ isShowShare } title="保存到相册" onClose={ this.shareClose }>
          <View className="share">
            <Image src={ QRCode2Base64 } />
          </View>
          <Button className="save-btn" disabled={ !isSave } onClick={ this.savePic }>保存图片</Button>
          <View className="tip-text">保存图片到手机相册后，将图片分享到您的圈子</View>
        </AtFloatLayout>
        <View className="share-pic">
          <canvas id="shareCanvas" canvas-id="shareCanvas"></canvas>
          <canvas id="shareQRCode" canvas-id="shareQRCode"></canvas>
        </View>
      </View>
    )
  }
}

export default Home